package com.gframework.boot.mvc.controller.protocal;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;

import com.gframework.boot.mvc.controller.errcode.ErrorCodeException;

/**
 * 前后端统一rest通讯格式处理接口.
 * 
 * @since 2.0.0
 * @author Ghwolf
 */
@SuppressWarnings("deprecation")
public interface RestResponseHandler {
	
	/**
	 * 将抛出的异常结果进行处理并返回
	 * @param e 异常对象
	 * @return 响应体
	 */
	public Object handleResult(Throwable e,HttpServletRequest request,HttpServletResponse response) ;
	
	/**
	 * 将一个正常返回的结果进行处理并返回
	 * @param obj 原始返回结果对象
	 * @return 响应体
	 */
	public Object handleResult(Object obj,HttpServletRequest request,HttpServletResponse response) ;
	
	/**
	 * 根据一个http状态号进行处理并返回
	 * @param httpStatus http状态号
	 * @return 响应体
	 */
	public Object handleResult(int httpStatus,HttpServletRequest request,HttpServletResponse response) ;
	
	/**
	 * 根据一个http状态对象进行处理并返回
	 * @param httpStatus http状态对象
	 * @return 响应体
	 */
	public Object handleResult(HttpStatus httpStatus,HttpServletRequest request,HttpServletResponse response) ;
	
	/**
	 * 处理404错误
	 * @return 响应体
	 */
	default Object handleNoHandlerFoundException(HttpServletRequest request,HttpServletResponse response) {
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		return new ErrorCodeException(404, 404, request.getRequestURI() + " Not Found");
	}
	
	/**
	 * 处理JSR验证错误
	 * @param e JSR验证错误信息封装对象
	 * @return 响应体
	 */
	default Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e,HttpServletRequest request,HttpServletResponse response) {

		List<ObjectError> errs = e.getBindingResult().getAllErrors();
		String msg = errs.isEmpty() ? e.getMessage() : errs.get(0).getDefaultMessage();

		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		
		return new ErrorCodeException(400,400, msg);
	}
	/**
	 * 处理JSR验证错误
	 * @param e JSR验证错误信息封装对象
	 * @return 响应体
	 */
	default Object handleBindException(BindException e,HttpServletRequest request,HttpServletResponse response) {
		
		List<ObjectError> errs = e.getBindingResult().getAllErrors();
		String msg = errs.isEmpty() ? e.getMessage() : errs.get(0).getDefaultMessage();
		
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

		return new ErrorCodeException(400,400, msg);
	}

}
